package com.gitee.dolt.sms;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import com.gitee.dolt.core.exception.InternalServerException;
import com.gitee.dolt.sms.event.SmsSendLogListener;
import com.gitee.dolt.sms.properties.SmsProperties;
import com.gitee.dolt.sms.enumeration.SmsType;
import com.gitee.dolt.sms.service.AliSmsService;
import com.gitee.dolt.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author LYH
 */
@Configuration
@EnableConfigurationProperties(SmsProperties.class)
@Slf4j
public class SmsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SmsSendLogListener smsSendLogListener() {
        return new SmsSendLogListener((optLogDTO) -> {
            log.debug("{}|{}", "SMS_SEND_LOG", JSONUtil.toJsonStr(optLogDTO));
        });
    }


    @ConditionalOnClass({Client.class})
    @Bean
    public SmsService aliSmsService(SmsProperties smsProperties) {
        if (SmsType.ALI.equals(smsProperties.getSmsType())) {
            Config config = new Config().setRegionId(smsProperties.getRegionId())
                    .setAccessKeyId(smsProperties.getAccessKey())
                    .setAccessKeySecret(smsProperties.getSecurityKey())
                    .setEndpoint("dysmsapi.aliyuncs.com");
            Client client;
            try {
                client = new Client(config);
            } catch (Exception e) {
                throw new InternalServerException("阿里云短信客户端构建异常", e);
            }
            return new AliSmsService(client, smsProperties);
        }
        return null;
    }

}
